package com.sqx.modules.timedtask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.modules.app.entity.UserVip;
import com.sqx.modules.app.service.UserVipService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.task.service.HelpOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class AutoSendOrder {
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private HelpOrderService helpOrderService;

    /**
     * 会员到期检测
     */
    @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai")
    public void userVipCheck() {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<UserVip> userVipList = userVipService.list(new QueryWrapper<UserVip>().eq("is_vip", 1));
        for (UserVip userVip : userVipList) {
            if (LocalDateTime.now().isAfter(LocalDateTime.parse(userVip.getEndTime(), fmt))) {
                userVip.setIsVip(2);
                userVipService.updateById(userVip);
            }
        }
    }

    @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai")
    public void cancelOrder() {
        //服务订单
        String value = commonInfoService.findOne(610).getValue();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Orders> ordersList = ordersService.list(new QueryWrapper<Orders>().eq("state", 0));
        for (Orders orders : ordersList) {
            LocalDateTime createTime = LocalDateTime.parse(orders.getCreateTime(), fmt);
            LocalDateTime expireTime = createTime.plusMinutes(Long.parseLong(value));
            if (LocalDateTime.now().isAfter(expireTime)) {
                orders.setState("3");
                ordersService.updateById(orders);
            }
        }
        //万能任务订单
        List<HelpOrder> helpOrderList = helpOrderService.list(new QueryWrapper<HelpOrder>().eq("status", 0));
        for (HelpOrder helpOrder : helpOrderList) {
            LocalDateTime createTime = LocalDateTime.parse(helpOrder.getCreateTime(), fmt);
            LocalDateTime expireTime = createTime.plusMinutes(Long.parseLong(value));
            if (LocalDateTime.now().isAfter(expireTime)) {
                helpOrder.setStatus(5);
                helpOrderService.updateById(helpOrder);
            }
        }

    }
}
